import gsap from 'gsap'
import * as THREE from 'three'
import {
    FBXLoader
} from 'three/examples/jsm/loaders/FBXLoader.js'
import {
    GLTFLoader
} from 'three/examples/jsm/loaders/GLTFLoader.js'


const manager = new THREE.LoadingManager()

export const loadManager = (pathList, suc) => {
    // 定义加载器对象
    const fbxLoader = new FBXLoader(manager)
    const gltfLoader = new GLTFLoader(manager)

    // 保存加载成功模型对象数组
    const model = []

    let preValue = 0 // 上一次加载的值

    // onProgress-每加载完一个模型都会触发一次
    manager.onProgress = (url, loadNum, totalNum) => {
        let progressRatio = Math.floor((loadNum / totalNum)) * 100

        // fromTo是从指定的值变化到目标的值，
        gsap.fromTo('#processing-number', {
            innerText: preValue
        }, {
            innerText: progressRatio,
            onUpdate () {
                // 找到dom标签对应的属性值，// this.targets()[0]就是#processing-number
                const num = gsap.getProperty(this.targets()[0], 'innerText')
                // 给这个dom拼接上百分号
                this.targets()[0].innerText = num + '%'
                preValue = progressRatio
                if (num === 100) {
                    // 如果加载完成，则把modle回传给调用使用loadManager的地方
                    suc(model)
                    document.querySelector('.loading').style.display = 'none'
                }
            }
        })
        // 进度条的加载动效
        gsap.fromTo('#loading-bar', {
            scaleX: preValue / 100
        }, {
            scaleX: progressRatio / 100,
        })
    }

    pathList.forEach(path => {
        if (path.indexOf('fbx') > -1) {
            fbxLoader.load(path, obj => {
                model.push({
                    model: obj,
                    url: path
                });
                // (model.length === pathList.length) && suc(model)
            })
        } 
        else if (path.indexOf('gltf') > -1) {
            gltfLoader.load(path, gltf => {
                model.push({
                    model: gltf.scene,
                    url: path
                });
                // (model.length === pathList.length) && suc(model)
            })
        }
    })
}